package hibari.client.ui;

import java.util.Arrays;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.InlineHTML;
import com.google.gwt.user.client.ui.RootPanel;

public class Tabs {
	private static Tabs instance;

	public static final int TAB_HOME = 0;
	public static final int TAB_ABOUT = 1;
	public static final int TAB_CONTACT = 2;

	public static Tabs getInstance() {
		return instance;
	}

	private SelectionHandler<Integer> tabHandler;

	private InlineHTML homeTab;

	private InlineHTML aboutTab;

	private InlineHTML faqTab;
	private InlineHTML activeTab;
	private InlineHTML[] tabs = null;
	private List<InlineHTML> tabList;

	public Tabs(RootPanel rootPanel) {
		this.homeTab = InlineHTML.wrap(RootPanel.get("home-tab").getElement());
		this.aboutTab = InlineHTML.wrap(RootPanel.get("about-tab").getElement());
		this.faqTab = InlineHTML.wrap(RootPanel.get("contact-tab").getElement());
		tabs = new InlineHTML[] { homeTab, aboutTab, faqTab };
		tabList = Arrays.asList(tabs);

		init();
	}

	public InlineHTML getActiveTab() {
		return activeTab;
	}

	public SelectionHandler<Integer> getTabHandler() {
		return tabHandler;
	}

	private void init() {
		for (final InlineHTML eachTab : tabs) {
			eachTab.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					setActiveTab(eachTab, true);
				}
			});
		}
	}

	public void setActiveTab(InlineHTML activeTab, boolean notify) {
		if (this.activeTab == activeTab) {
			return;
		}
		this.activeTab = activeTab;
		for (InlineHTML each : tabs) {
			if (each == activeTab) {
				each.addStyleName("active-tab");
			} else
				each.removeStyleName("active-tab");
		}

		int index = tabList.indexOf(activeTab);
		if (tabHandler != null && notify) {
			tabHandler.selectionChanged(index);
		}
	}

	public void setActiveTab(int index) {
		setActiveTab(tabList.get(index), false);
	}

	public void setTabHandler(SelectionHandler<Integer> tabHandler) {
		this.tabHandler = tabHandler;
	}
}
